import Vue from 'vue'
import {
  ToastPlugin
} from 'vux'
Vue.use(ToastPlugin)
const websocket = new Vue({
  data() {
    return {
      userInfo:'',
      ws: '',
      usertel:'',   // 当前的分机号
      exPhoneGroup:['3584','3580'],   //  特殊处理的分机号
      userInfo: '',
      state: 0,
      data: {},
      keepalive: '',
      //  属于call-center页面，判断是否已发送
      callCenter: true,
      pickup:false, // 用来标记是否摘机
      callin:false,
      outPhone: '', // 播出的外接号码
      zjid: '', // 转接的id
      TalkPhone: '', // 转接的外线号码
      transferPhone: '' // 转接的内线号码
    }
  },
  watch: {
    state: function (val) {
      console.log('websocket:', val)
      if (val === 1) {
        this.keepAliveHandle()
      } else {
        this.reset();
      }
    }
  },
  methods: {
    init(userInfo) {
      if(!userInfo){
        return
      }
      this.userInfo = userInfo
      this.ws = new WebSocket("ws://122.228.132.78:6688");
      this.ws.onopen = this.WSonOpen;
      this.ws.onmessage = this.WSonMessage;
      this.ws.onclose = this.WSonClose;
      this.ws.onerror = this.WSonError;
    },
    WSonOpen() {
      const {power,userGroup} = this.userInfo
      this.$vux.toast.show({
        text: '开始连接',
        type: 'text'
      })
      this.WsSend('login')
      // 如果权限为3则不发送openseatlist
      if(power < 3){
        setTimeout(()=>{
          this.WsSend('openseatlist')
        },100)
        setTimeout(()=>{
          this.WsSend('openqueues')
        },200)
      }
      if(userGroup === '质检组'){
        setTimeout(()=>{
          this.WsSend('calllist')
        },300)
      }
    },
    WsSend: function (s) {
      // console.log('发出',this.createJson(s))
      this.ws.send(this.createJson(s))
    },
    WSonMessage(evt) {
      
      this.state = this.ws.readyState
      if (typeof (evt.data) == "string") {
        this.textHandler(evt.data);
      } else {
        var reader = new FileReader();
        reader.readAsText(evt.data);
        reader.onload = (e) => {
          if (e.target.readyState == FileReader.DONE) {
            
            this.textHandler(e.target.result); //协议返回
          }
        }
      }
    },
    WSonClose() {
      this.$vux.toast.show({
        text: '连接结束',
        type: 'text'
      })
      this.reset();
    },
    WSonError() {
      this.$vux.toast.show({
        text: '连接出错',
        type: 'text'
      })
      this.reset();
    },
    textHandler(data) {
      // console.log('返回',data)
      this.data = JSON.parse(data)
    },
    createJson: function (cmd) {
      /**
       * outPhone 播出的外接号码
       * zjid 转接的id
       * TalkPhone 转接的外线号码
       * transferPhone 转接的内线号码
       */
      const outPhone = this.outPhone
      const zjid = this.zjid
      const TalkPhone = this.TalkPhone
      const transferPhone = this.transferPhone
      const ex = this.exOutPhone()
      var req = "";
      if (cmd == "login") //登陆
      {
        req = "{\"cmd\":\"system\",\"action\":\"login\",\"username\":\"" + this.userInfo.usertel + "\",\"password\":\"" + this.userInfo.psd + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "keepalive") //60s 发送一次握手
      {
        req = "{\"cmd\":\"system\",\"action\":\"keepalive\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "afk") //置忙（暂离）
      {
        req = "{\"cmd\":\"control\",\"action\":\"afk\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "online") //在线
      {
        req = "{\"cmd\":\"control\",\"action\":\"online\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "out") //发起外呼
      {
        req = "{\"cmd\":\"callout\",\"action\":\"out\",\"phone\":\"" + this.fullNumber(outPhone, ex) + "\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "transfer") //通话转接
      {
        req = "{\"cmd\":\"control\",\"action\":\"transfer\",\"id\":\"" + zjid + "\",\"phone\":\"" + TalkPhone + "\",\"transfernum\":\"" + transferPhone + "\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "transferresume") //通话转接收回
      {
        req = "{\"cmd\":\"control\",\"action\":\"transferresume\",\"id\":\"" + zjid + "\",\"phone\":\"" + TalkPhone + "\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "pickup") //摘机
      {
        req = "{\"cmd\":\"control\",\"action\":\"pickup\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "hangup") //挂机
      {
        req = "{\"cmd\":\"control\",\"action\":\"hangup\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "seatinit") //座席呼叫状态重置协议
      {
        req = "{\"cmd\":\"control\",\"action\":\"seatinit\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "openseatlist") //当前所有坐席状态
      {
        req = "{\"cmd\":\"status\",\"action\":\"openseatlist\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "openqueues") //当前所有排队队列信息
      {
        req = "{\"cmd\":\"status\",\"action\":\"openqueues\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      } else if (cmd == "calllist") //当前所有通话信息
      {
        req = "{\"cmd\":\"status\",\"action\":\"calllist\",\"username\":\"" + this.userInfo.usertel + "\",\"timestamp\":\"" + this.timestamp() + "\"}";
      }
      return req;
    },
    exOutPhone(){
      const exPhoneGroup = this.exPhoneGroup
      const usertel = this.usertel
      if(exPhoneGroup.includes(usertel)){
        return '0'
      }
      return '9'
    },
    timestamp() {
      var tmp = Math.round(new Date().getTime() / 1000);
      return tmp;
    },
    keepAliveHandle() {
      this.keepalive = setInterval(() => {
        this.WsSend('keepalive')
      // }, 30 * 1000);
      }, 3 * 1000);
    },
    stopKeepAlive() {
      clearInterval(this.keepalive)
    },
    reset() {
      this.state = 0;
      this.stopKeepAlive();
    },
    fullNumber: function (strV, num) {
      if (strV != "") {
        if (strV[0] != num)
          strV = num + strV;
      }
      return strV;
    }
  }
})
window.websocket = websocket
export default websocket
